package com.bkhech.nettyhttp.client;

import com.bkhech.nettyhttp.server.HttpServer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

/**
 * HttpClient
 *
 * @author guowm
 * @date 2024/4/1
 */
public class HttpClient {
    public static final String HOST = "127.0.0.1";

    public void connect(String host, int port) throws Exception {
        SslContext sslContext = createSslContext();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    if (sslContext != null) {
                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc(), host, port));
                    }
                    ch.pipeline().addLast(new HttpClientCodec());
                    /*这个聚合器主要是将 HttpMessage 聚合成http为一个完整的报文，即 FullHttpRequest/FullHttpResponse*/
                    ch.pipeline().addLast("aggregator",
                            new HttpObjectAggregator(10 * 1024 * 1024));
                    /*解压缩*/
                    ch.pipeline().addLast("decompressor",
                            new HttpContentDecompressor());
                    ch.pipeline().addLast(new HttpClientInboundHandler());
                }
            });

            // Start the client.
            ChannelFuture f = b.connect(host, port).sync();

            // 获取 Channel, 可用于业务处理
            final Channel channel = f.channel();

            // 等待连接被关闭
            channel.closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * 注意：这个示例使用了InsecureTrustManagerFactory来信任所有的服务器证书，
     * 这在开发和测试阶段很有用，但在生产环境中需要使用安全的证书管理策略。
     * 在真实环境中，为了确保通信的安全性，你应该使用有效的服务器证书来建立SSL/TLS连接，
     * 而不是使用InsecureTrustManagerFactory来信任所有的服务器证书
     * <p>
     * {@link SslContextFactoryForClient}
     * {@link SslContextFactoryMutualAuthForClient}
     *
     * @return
     */
    private SslContext createSslContext() {
        if (HttpServer.SSL) {
            System.out.println("服务器处于SSL模式，客户端加载服务器的证书");
            try {
                return SslContextBuilder.forClient()
                        .trustManager(InsecureTrustManagerFactory.INSTANCE)
                        .build();
            } catch (Exception e) {

            }
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        HttpClient client = new HttpClient();
        client.connect("127.0.0.1", HttpServer.port);
    }
}
